#include <ESP8266WiFi.h>
 
/*** 该工程可以在2.4.0版本esp8266库中运行，没在更高版本库中进行测试 ***/
 
const char *ssid = "Ronghe";
const char *password = "12345678";

const int DIRECTION_PIN = 4;  //D2
const int SPEED_PUL_PIN = 5;  //D1

const int MOVE_FORW_PIN = 12; //D6
const int MOVE_BACK_PIN = 13; //D7

const int LED_FORW_PIN = 14;  //D5
const int LED_BACK_PIN = 15;  //D8

bool MOVE_DIRECTION = true;   //move direction true=forward ; false=back
int  MOVE_SPEED = 1;          //speed default 0-1023 / 0=stop, 1->1023 min to quickly and max to slow;
int  ONCE_SETPS = 6;         //Once move opration,to move setps.



WiFiServer server(80);
 
String readString = ""; //建立一个字符串对象用来接收存放来自客户的数据
 
//响应头
String responseHeaders =
    String("") +
    "HTTP/1.1 200 OK\r\n" +
    "Content-Type: text/html\r\n" +
    "Connection: close\r\n" +
    "\r\n";
 
//网页
String myhtmlPage =
    String("") +
    "<html>" +
    "<head>" +
    "    <title>SmartCtrol For DM542 Stepper Driver By ESP8266 Web</title>" +   
    "    <style>" +   
    "        .inline{" +
    "            display:inline;" +
    "        }" + 
    "        .on{" +
    "            background-color:#66ff66;" +
    "        }" + 
    "        .off{" +
    "            background-color:#669966;" +
    "        }" +   
    "    </style>" +   
    "    <script defer=\"defer\">" +
    "        function Switch() {" +
    "            var xmlhttp;" +
    "            if (window.XMLHttpRequest) {" +
    "                xmlhttp = new XMLHttpRequest();" +
    "            } else {" +
    "                xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");" +
    "            }" +
    "            xmlhttp.onreadystatechange = function () {" +
    "                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {" +
    "                    document.getElementById(\"txtState\").innerHTML = xmlhttp.responseText;" +
    "                }" +
    "            }," +
    "            xmlhttp.open(\"GET\", \"Switch\", true);" +
    "            xmlhttp.send(); " +
    "        }" +
    "        function Move() {" +
    "            var xmlhttp;" +
    "            if (window.XMLHttpRequest) {" +
    "                xmlhttp = new XMLHttpRequest();" +
    "            } else {" +
    "                xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");" +
    "            }" +
    "            xmlhttp.onreadystatechange = function () {" +
//    "                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {" +
//    "                    document.getElementById(\"txtState\").innerHTML = xmlhttp.responseText;" +
//    "                }" +
    "            }," +
    "            xmlhttp.open(\"GET\", \"Move\", true);" +
    "            xmlhttp.send(); " +
    "        }" +
    "    </script>" +
    "</head>" +
    "<body><center>" +
    "    <input class=\"inline\" type=\"button\" value=\"<= Change Direction =>\" onclick=\"Switch()\">" +
    "    <input class=\"inline\" type=\"button\" value=\"<= Move Some Stepes =>\" onclick=\"Move()\">" +
    "  <hr/>" +
    "  <span class=\"inline off\">|=================================</span><span class=\"inline on\" id=\"txtState\">===</span><span class=\"inline off\">=================================|</span>" +
    "  </center>" +
    "</body>" +
    "</html>";
 

 
void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    pinMode(LED_FORW_PIN, OUTPUT); 
    pinMode(LED_BACK_PIN, OUTPUT); 
    pinMode(DIRECTION_PIN, OUTPUT); 
    pinMode(SPEED_PUL_PIN, OUTPUT); 

    pinMode(MOVE_FORW_PIN, INPUT); 
    pinMode(MOVE_BACK_PIN, INPUT); 
    
    digitalWrite(LED_BUILTIN, HIGH); // 熄灭LED
 
    Serial.begin(115200);
    Serial.println();
 
    Serial.printf("Connecting to %s ", ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println(" connected");
 
    server.begin();
    Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}

void change_direction(){
  
  MOVE_DIRECTION = !MOVE_DIRECTION;
  if (MOVE_DIRECTION == true){
    digitalWrite(LED_FORW_PIN, HIGH);
    digitalWrite(LED_BACK_PIN, LOW);
    digitalWrite(DIRECTION_PIN, HIGH);
    Serial.println("move forward.");
    //delay(300);
  }else{
    digitalWrite(LED_FORW_PIN, LOW);
    digitalWrite(LED_BACK_PIN, HIGH);
    digitalWrite(DIRECTION_PIN, LOW);
    Serial.println("change back.");
    //delay(300);
  }
}

void move(){
  //move only 
  analogWrite(SPEED_PUL_PIN, 1);
  for (int i = 0; i < ONCE_SETPS; i++)
  {
    delay(100);
  }
  analogWrite(SPEED_PUL_PIN, 0);
}


 
void loop()
{
    WiFiClient client = server.available(); //尝试建立客户对象
    if (client)                             //如果当前有客户可用
    {
        boolean currentLineIsBlank = true;
        Serial.println("[Client connected]");
 
        while (client.connected()) //如果客户端建立连接
        {
            if (client.available()) //等待有可读数据
            {
                char c = client.read(); //读取一字节数据
                readString += c;        //拼接数据
                /************************************************/
                if (c == '\n' && currentLineIsBlank) //等待请求头接收完成(接收到空行)
                {
                    //比较接收到的请求数据
                    if (readString.startsWith("GET / HTTP/1.1")) //如果是网页请求
                    {
                        client.print(responseHeaders); //向客户端输出网页响应
                        client.print(myhtmlPage);      //向客户端输出网页内容
                        client.print("\r\n");
                    }
                    else if (readString.startsWith("GET /Switch")) //如果是改变LED状态请求
                    {
                        if (MOVE_DIRECTION == false)
                        {
                            change_direction();
                            client.print(">>>");
                        }
                        else
                        {
                           change_direction();
                           client.print("<<<");
                        }
                    }
                    else if (readString.startsWith("GET /Move")) //如果是改变LED状态请求
                    {
                        move();
                    }
                    else
                    {
                        client.print("\r\n");
                    }
                    break;
                }
 
                if (c == '\n')
                {
                    currentLineIsBlank = true; //开始新行
                }
                else if (c != '\r')
                {
                    currentLineIsBlank = false; //正在接收某行中
                }
                /************************************************/
            }
        }
        delay(1);      //等待客户完成接收
        client.stop(); //结束当前连接:
        Serial.println("[Client disconnected]");
 
        Serial.println(readString); //打印输出来自客户的数据
        readString = "";
    }
    
    
}
